package com.tools.cleanmaster.ui.base;

import android.os.Bundle;

import java.lang.ref.WeakReference;
import java.util.WeakHashMap;

/**
 * 单一页面，新开面开启时，如果以存在，会立即关闭新开的页面
 */
public abstract class SingleActivity extends BaseActivity {

    private static WeakHashMap<String, WeakReference<SingleActivity>> sInstanceList = new WeakHashMap<String, WeakReference<SingleActivity>>();

    private final String mActivityName = getClass().getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SingleActivity instance = getSingleActivity(mActivityName);
        if (instance != null) {
            instance.finish();
        }

        synchronized (sInstanceList) {
            sInstanceList.put(mActivityName, new WeakReference<SingleActivity>(this));
        }
    }

    private SingleActivity getSingleActivity(String name) {
        WeakReference<SingleActivity> ref = sInstanceList.get(name);
        if (ref != null) {
            return ref.get();
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SingleActivity instance = getSingleActivity(mActivityName);
        if (instance == this) {
            synchronized (sInstanceList) {
                sInstanceList.remove(mActivityName);
            }
        }
    }
}
